const querystring = require('querystring')
const createRouter = require('router')
const router = createRouter()

// 模板引擎
const { template } = require('./template')

const { Student } = require('../model/Student')

router.get('/add', (req, res) => {
  const html = template('add', {})
  res.end(html)
})

router.post('/add', (req, res) => {
  let data = ''
  req.on('data', chunk => {
    data += chunk
  })
  req.on('end', async () => {
    data = querystring.parse(data)
    console.log(data)
    await Student.create(data)
    res.writeHead(301, { Location: '/list' })
    res.end()
  })
})

router.get('/list', async (req, res) => {
  const studentArr = await Student.find()
  const html = template('list', { studentArr })
  res.end(html)
})

module.exports = {
  router
}
